/**
 * @title Swagger类
 * @Author webxue
 * @Date 2022/12/01
 */

import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "src/app.module";

export class SwaggerLib {
  private app = null;
  private title = "API文档";
  private description = "API文档";
  private version = "1.0";
  private url = "/doc/api";

  constructor(option: SwaggerProp) {
    this.app = option.app;
    if (option.title) this.title = option.title;
    if (option.description) this.description = option.description;
    if (option.version) this.version = option.version;
    if (option.url) this.url = option.url;
  }

  // 构建swagger
  build() {
    // 实例化文档生成器
    const swaggerOptions = new DocumentBuilder()
      // 设置文档标题
      .setTitle(this.title)
      // 设置文档描述
      .setDescription(this.description)
      // 设置文档版本号
      .setVersion(this.version)
      // 添加鉴权
      .addBearerAuth()
      // 生成参数
      .build();
    // 调用SwaggerModule的的createDocument方法，将NestFactory创建的主程序和Swagger参数传入生成文档
    const document = SwaggerModule.createDocument(this.app, swaggerOptions);
    // 设置文档访问地址为/doc
    SwaggerModule.setup(this.url, this.app, document);
  }
}

// Swagger实例属性
interface SwaggerProp {
  app: AppModule;
  title?: string;
  description?: string;
  version?: string;
  url?: string;
}
